import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tvlives/http/live_api.dart';
import 'package:tvlives/model/LiveRoom.dart';

class LiveList extends StatefulWidget{
  final String cid;
  final String com;
  const LiveList({Key key,this.cid,this.com}) :super(key:key);


  @override
  State<StatefulWidget> createState() {
    return _LiveListState();
  }
}

class _LiveListState extends State<LiveList> with AutomaticKeepAliveClientMixin{

  List<LiveRoom> _listRooms = [];
  RefreshController _refreshController = RefreshController(initialRefresh: true);
  int _pageNum = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
      super.initState();
  }


  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  //下拉刷新
 void _onRefresh() async {
    var list = [];
    try{
      if(widget.com == "all"){
          list = await LiveAPI.getRecommendAll(widget.cid, 1);
      }else{
         list = await LiveAPI.getRecommendByCom(widget.com, 1);
      }
      setState(() {
        _listRooms = list;
      });
      if(_listRooms!=null){
        _refreshController.refreshCompleted();
      }
    }catch(e){
      print(e);
      _refreshController.refreshFailed();
   }
 }

  //上拉加载
 void _onLoading() async{
    List<LiveRoom> list = [];
    if(widget.com=="all"&&widget.cid =="0"){
      list = await LiveAPI.getRecommendAll(widget.cid, _pageNum+1);
    }else{
      list = await LiveAPI.getRecommendByCom(widget.com, _pageNum+1);
    }

    setState(() {
      _pageNum++;
      _listRooms.addAll(list);
    });
    _refreshController.loadComplete();
 }

  @override
  Widget build(BuildContext context) {
     super.build(context);
     return SmartRefresher(
       enablePullDown: true,
       enablePullUp: true,
       controller: _refreshController,
       onRefresh: _onRefresh,
       onLoading: _onLoading,
       footer: ClassicFooter(
         loadStyle: LoadStyle.ShowWhenLoading,
         loadingText: "Loading",
       ),
       child: ListView.builder(
           physics: BouncingScrollPhysics(),
           itemCount: _listRooms.length,
           itemBuilder: (context,index){
             return buildCard(_listRooms[index]);
           }),
     );
  }

  Widget buildCard(LiveRoom room){
        var width = MediaQuery.of(context).size.width;
        var stack = new Stack(
          alignment: AlignmentDirectional.bottomCenter,
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: room.roomThumb,
              fit:BoxFit.fitWidth,
              width: width,
              placeholder: (context,url){
                return Image.asset("assets/images/cache.png",fit: BoxFit.fitWidth,width: width,);
              },
              errorWidget: (context,url,error){
                return Image.asset("assets/images/cache.png",fit: BoxFit.fitWidth,width: width,);
              },
            ),
            new Container(
              width: 400,
              height: 50,
              padding: const EdgeInsets.all(5),
              alignment: Alignment.bottomLeft,
              decoration: new BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black12,
                    Colors.black54,
                  ]
                )
              ),
              child: Row(
                 children: <Widget>[
                   Expanded(
                     flex: 1,
                     child: new Text(
                       room.cateName,
                       style: new TextStyle(
                         fontSize: 15,
                         color: Colors.white,
                       ),
                     ),
                   ),
                   new Icon(
                     Icons.whatshot,
                     color:Colors.white70,
                     size:20,
                   ),
                   new Text(
                       convertOnline(room.online),
                       style: new TextStyle(
                         fontSize: 15,
                         color:Colors.white,
                       ),
                   ),
                 ],
              ),
            ),
          ],
        );
        return Card(
            child: InkWell(
                splashColor: Colors.blue.withAlpha(30),
                onTap: () {

                },
                child: Column(
                  children: <Widget>[
                    stack,
                    ListTile(
                      contentPadding: const EdgeInsets.only(left: 5),
                      leading: ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: Image.network(room.avatar,
                              fit: BoxFit.fill, width: 50, height: 50)),
                      title: Text(
                        convertCom(room.com) + '·' + room.ownerName,
                        overflow: TextOverflow.ellipsis,
                      ),
                      subtitle: Text(
                        room.roomName,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                )));

  }

  String convertOnline(int online) {
    if (online >= 10000) {
      //dart 截断运算符
      return (online ~/ 10000).toString() + "万";
    }
    return online.toString();
  }

  String convertCom(String com) {
    switch (com) {
      case 'douyu':
        return "斗鱼";
      case 'bilibili':
        return "B站";
      case 'huya':
        return "虎牙";
      case 'egame':
        return"企鹅电竞";
      default:
        return "未知";
    }
  }
}